<template>
  <page-meta
    :page-style="
      visible || skuVisible || preferenceVisible
        ? 'overflow:hidden'
        : 'overflow:auto'
    "
  />
  <view v-if="!loading" class="cart">
    <!--  购物车为空显示  -->
    <empty-cart v-if="!isShowCart" />
    <!--  购物车存在数据  -->
    <shopping-cart
      v-if="isShowCart"
      :info="info"
      :allSelect="allSelect"
      :preferenceVisible="preferenceVisible"
      @sku-change="onChooseSku"
      @openVisible="openVisible"
      @getInfo="getCartInfo"
      @showDetail="openDetail"
    />
    <!-- 购物车更多商品 -->
    <recommend-goods :listData="goodsList" />
    <!-- SKU选择 -->
    <oreo-popup round :show="skuVisible" position="bottom">
      <product-sku
        :product="currentProduct"
        @confirm="onChangeSku"
        @close="skuVisible = false"
      />
    </oreo-popup>

    <!-- 优惠券选择列表 -->
    <oreo-popup :show="visible" round position="bottom">
      <goods-coupon-list
        @close="onCloseCoupon"
        :couponList="couponList"
        @getGoodsCoupon="getAllCoupon"
        @getCartInfo="getCartInfo"
      />
    </oreo-popup>
    <!-- 优惠明细 -->
    <oreo-popup
      class="preference"
      :show="preferenceVisible"
      round
      position="bottom"
    >
      <preference-detail :info="info" @close="preferenceVisible = false" />
    </oreo-popup>
  </view>
  <tab-bar-divider />
  <custom-tab-bar :current="4" :cartCount="cartCount" />


</template>

<script setup>
import EmptyCart from "@/components/empty-cart.vue";
import ShoppingCart from "@/components/shopping-cart.vue";
import { GetCartInfo } from "@/services/mall";
import {
  UpdateCartSku,
  UpdateCartQuantity,
  GetCartGoods,
} from "@/services/cart";
import { ref } from "vue";
import {
  onLoad,
  onShow,
  onUnload,
  onHide,
  onPullDownRefresh,
} from "@dcloudio/uni-app";
import ProductSku from "@/components/product-sku";
import TabBarDivider from "@/components/tab-bar-divider";
import CustomTabBar from "@/components/custom-tab-bar";
import GoodsCouponList from "@/components/goods-coupon-list";
import { GetAllCouponList } from "@/services/coupon";
import PreferenceDetail from "@/components/preference-detail";
import RecommendGoods from "@/components/recommend-goods.vue";
import privacyPopup from "@/components/privacy-popup";

let enterTime = "";
let outTime = "";
let stayTime = "";

const skuVisible = ref(false);
const visible = ref(false);
const currentProduct = ref({});

const isShowCart = ref(false);
const couponList = ref([]);
const loading = ref(true);
const allSelect = ref(false);
const info = ref({
  items: [],
});
const goodsList = ref([]);
const preferenceVisible = ref(false);
const cartCount = ref(getApp().globalData.cartCount);

onShow(() => {
  // 用户进入时间
  enterTime = new Date();
  getInfo();
  if (uni.getStorageSync("TOKEN")) {
    getApp()
      .getUserInfo()
      .then(() => {});
  }

  getApp().accessLogAdd();
});

onHide(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  getApp().emdlz2("track", "event", "store_page", "view", "cart_page", stayTime);
});

onUnload(() => {
  // 用户退出时间
  outTime = new Date();
  //停留时间(毫秒)
  stayTime = (outTime.getTime() - enterTime.getTime()) / 1000;
  getApp().emdlz2("track", "event", "store_page", "view", "cart_page", stayTime);
});

onPullDownRefresh(() => {
  console.log("refresh");
  getInfo();
});

const onCloseCoupon = () => {
  console.log(111);
  visible.value = false;
};

const openVisible = (value) => {
  console.log(value);
  uni.pageScrollTo({
    duration: 0, //过渡时间必须为0，uniapp bug，否则运行到手机会报错
    scrollTop: 10, //滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
  });
  visible.value = value;
  for (const item of couponList.value) {
    getApp()
      .sr()
      .track("expose_coupon", {
        coupon: [
          {
            coupon_id: item.id,
            coupon_name: item.name,
          },
        ],
        coupon_package: {
          coupon_package_id: item.id,
          coupon_package_name: item.name,
        },
        coupon_batch: {
          coupon_batch_id: item.id,
          coupon_batch_name: item.name,
        },
        // more...
      });
  }
};

const openDetail = (value) => {
  console.log(value);
  uni.pageScrollTo({
    duration: 0, //过渡时间必须为0，uniapp bug，否则运行到手机会报错
    scrollTop: 10, //滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
  });
  preferenceVisible.value = value;
};

const onChooseSku = (value) => {
  console.log(value);
  uni.pageScrollTo({
    duration: 0, //过渡时间必须为0，uniapp bug，否则运行到手机会报错
    scrollTop: 10, //滚动到实际距离是元素距离顶部的距离减去最外层盒子的滚动距离
  });
  currentProduct.value = value;
  skuVisible.value = true;
};

// 修改SKU
const onChangeSku = async ({ productSkuId, quantity }) => {
  await UpdateCartSku({
    productSkuId,
    id: currentProduct.value.id,
  });
  await UpdateCartQuantity({ id: currentProduct.value.id, quantity });
  skuVisible.value = false;
  getInfo();
};

const getInfo = () => {
  loading.value = true;
  getCartInfo();
  getCartGoods();
  getAllCoupon();
  uni.stopPullDownRefresh();
};

const getAllCoupon = async () => {
  const res = await GetAllCouponList({ pageNum: 1, pageSize: 500 });
  if (res?.code === 200) {
    couponList.value = res.data.list;
  }
};

const getCartInfo = async () => {
  const res = await GetCartInfo();
  if (res?.code === 200) {
    loading.value = false;
    isShowCart.value = res.data.items && res.data.items.length;
    info.value = res.data;
    allSelect.value = info.value.items?.every((item) => item.selected === true);
    getApp()
      .getCartCount()
      .then((res) => {
        cartCount.value = res;
      });
  }
};

const getCartGoods = async () => {
  const res = await GetCartGoods();
  if (res?.code === 200) {
    goodsList.value = res.data.list;
  }
};
</script>

<style lang="less" scoped>
@import "@/static/css/theme.less";

.cart {
  width: 100%;
  min-height: 100vh;
  background-color: white;
  // padding: 12px;
  box-sizing: border-box;
}

:deep(.van-popup) {
  z-index: 1002 !important;
}

.preference {
  :deep(.van-popup) {
    margin-bottom: calc(constant(safe-area-inset-bottom) + 100px);
    margin-bottom: calc(env(safe-area-inset-bottom) + 100px);
  }
}
</style>
